package fileexplorer.commands;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import fileexplorer.Tools;
import fileexplorer.View;

public class Coller extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
	    View view = (View) page.findView(View.ID);
	    //System.out.println(view.getParentUrl());

	    paste(view);

		return null;
	}

	public static void paste(View view) {
		
		String urlDest = ""; //$NON-NLS-1$
	    if(view.getFileObjectSelected().size()==1){
	    	urlDest = view.getFileObjectSelected().get(0).getPath();
	    }else if(view.getFileObjectSelected().size()>0){
	    	// Message d'Erreur -> faire une popup !
	    	Tools.MessageErreur(view.shell, Messages.Coller_ItHadToHaveOnlyOneFolderToDestination);
	    }else{
	    	urlDest = view.getUrl();
	    }
	    
	    Clipboard clipboard = new Clipboard(view.shell.getDisplay());
	    String[] data = (String[]) clipboard.getContents(FileTransfer
				.getInstance());
	   
	    
		File sourceFile = new File(data[0]);
		System.out.println(data[0]);
		
		String separator = System.getProperty("file.separator"); //$NON-NLS-1$
		String newFile;
		if(urlDest.endsWith(separator)){
			newFile = urlDest+sourceFile.getName();
		}else{
			newFile = urlDest+separator+sourceFile.getName();
		}
		
		File destFile = new File(newFile);
		System.out.println(newFile);
		 
		try {
			Files.copy(sourceFile.toPath(),new FileOutputStream(destFile));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

}
